<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>配置文件处理</title>
    <link rel="stylesheet" href="lsy-css/lsy_button_css.css">
    <link rel="stylesheet" href="lsy-css/lsy_alert_css.css">
    <link rel="stylesheet" href="lsy-css/lsy_textarea_css.css">
    <link rel="stylesheet" href="lsy-css/lsy_dropdown_button_css.css">
    <link rel="stylesheet" href="lsy-css/lsy_prompt_css.css">

</head>

<body>
<h1 id="tipHead" style="text-align: center;">配置文件处理</h1>
<div id="buttonDiv">
    <div class="buttonStylish" onclick="http_post('get_config')">查询</div>
    <div class="buttonStylish" onclick="http_post('set_config')">保存</div>
    <div class="buttonStylish" onclick="json_format()">Json格式整理</div>
</div>

<div class="dropdown-container" style="display: flex;">
    <div class="dropdown">
        <button id="nameButton" class="dropdown-btn" onmouseover="renderMenu()">选择配置</button>
        <label id="nameLabel">配置名</label>
        <div id="nameMenu" class="dropdown-content" style="width: 15%">
            <!-- Menu items will be inserted here dynamically -->
        </div>
    </div>
</div>
<div id="configPathDiv" style="display: flex; align-items: center; margin-top: 10px">
    <div id="configPathShow" class="textareaTwo" style="width: 50%; height: 25px; font-size: 16px; line-height: 25px;">
        config.json
    </div>
</div>

<textarea id="customTextarea" class="textareaOne" spellcheck="false"></textarea>

<!-- 提示框及遮罩层 -->
<div class="alertOverlay" onclick="closeAlert()"></div>
<div class="alertBox">
    <h2>提示</h2>
    <p>这里是提示内容</p>
    <button onclick="closeAlert()">确定</button>
</div>

<!--输入框-->
<div id="custom-prompt" class="prompt-container">
    <div class="prompt-box">
        <div id="prompt-message"></div>
        <form id="prompt-form">
            <!-- Input fields will be dynamically inserted here -->
        </form>
        <div class="prompt-buttons">
            <button id="confirm-button">Confirm</button>
            <button id="cancel-button">Cancel</button>
        </div>
    </div>
</div>

<!--脚本-->
<!--控制文本使用tab时，缩进4格-->
<script>
    document.getElementById("customTextarea").addEventListener('keydown', function (e) {
        if (e.key === 'Tab') {
            e.preventDefault();

            const start = this.selectionStart;
            const end = this.selectionEnd;

            this.value = this.value.substring(0, start) + '    ' + this.value.substring(end);

            this.selectionStart = this.selectionEnd = start + 4;
        }
    })
</script>

<!--提示框-->
<script>
    function showAlert(message, headerTip = '提示') {
        document.querySelector('.alertBox h2').textContent = headerTip;
        document.querySelector('.alertBox p').textContent = message;
        document.querySelector('.alertOverlay').style.display = 'block';
        document.querySelector('.alertBox').style.display = 'block';
    }

    function closeAlert() {
        document.querySelector('.alertOverlay').style.display = 'none';
        document.querySelector('.alertBox').style.display = 'none';
    }
</script>

<!--http post交互-->
<script>
    let messageID = 0;

    function http_post(method, menuItems = null) {
        let jsonData;
        try {
            jsonData = JSON.parse(document.getElementById('customTextarea').value);
        } catch (error) {
            jsonData = null;
        }

        let sendData = {
            "id": messageID,
            "timeStamp": Date.now(),
            "method": method,
            "name": document.getElementById('nameLabel').innerText,
            "path": document.getElementById('configPathShow').innerText,
            "data": jsonData,
        }

        fetch('http://127.0.0.1:10100/handle-config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(sendData)
        })
            .then(response => response.json())
            .then(data => {
                if (typeof data.data === "object" && data.result === true) {
                    if (method === 'query_config') {
                        for (const key in data.data) {
                            let subItem = {id: data.data[key], label: key};
                            menuItems.push(subItem);
                        }
                    } else {
                        showAlert("处理成功", "成功")
                        document.getElementById('customTextarea').value = JSON.stringify(data.data, null, 4);
                    }
                } else {
                    throw new Error(data.reason);
                }
            })
            .catch(error => {
                showAlert(error, "失败")
            })
        messageID++;
    }
</script>

<!--输入框-->
<script>
    function showPrompt(message, inputs, callback) {
        const promptContainer = document.getElementById('custom-prompt');
        const promptMessage = document.getElementById('prompt-message');
        const promptForm = document.getElementById('prompt-form');
        promptMessage.textContent = message;

        // Clear previous inputs
        promptForm.innerHTML = '';

        // Add new input fields
        inputs.forEach(input => {
            const inputLabel = document.createElement('label');
            inputLabel.textContent = input.label;
            const inputField = document.createElement('input');
            inputField.type = input.type || 'text';
            inputField.name = input.name;
            inputField.required = input.required || false;
            inputLabel.appendChild(inputField);
            promptForm.appendChild(inputLabel);
            promptForm.appendChild(document.createElement('br'));
        });

        // Show the prompt
        promptContainer.style.display = 'flex';

        // Handle Confirm button click
        document.getElementById('confirm-button').onclick = function () {
            const formData = new FormData(promptForm);
            const data = {};
            formData.forEach((value, key) => {
                data[key] = value;
            });
            callback(data);
            promptContainer.style.display = 'none';
        };

        // Handle Cancel button click
        document.getElementById('cancel-button').onclick = function () {
            promptContainer.style.display = 'none';
        };
    }
</script>

<!--加载菜单-->
<script>
    let menuItems = [];

    // 渲染菜单项
    function renderMenu() {
        const pathTextarea = document.getElementById('configPathShow');
        const nameLabelText = document.getElementById('nameLabel');
        const dropdownMenu = document.getElementById('nameMenu');
        dropdownMenu.innerHTML = '';

        menuItems.forEach(item => {
            const menuItem = document.createElement('div');
            menuItem.className = 'menu-item';

            const link = document.createElement('a');
            link.href = "#";
            link.textContent = item.label;

            // 替换路径
            link.addEventListener('click', () => {
                nameLabelText.innerText = item.label;
                pathTextarea.innerText = item.id;
            });

            const deleteButton = document.createElement('button');
            deleteButton.textContent = '删除';
            deleteButton.className = 'delete-btn';
            deleteButton.addEventListener('click', () => {
                menuItems = menuItems.filter(i => i.label !== item.label);
                renderMenu();
                http_post('del_config')
            });

            menuItem.appendChild(link);
            menuItem.appendChild(deleteButton);
            dropdownMenu.appendChild(menuItem);
        });

        // 添加一个添加项的按钮
        const addItem = document.createElement('a');
        addItem.href = "#";
        addItem.textContent = '+ 添加新项';
        addItem.className = 'add-item';
        addItem.addEventListener('click', () => {
            showPrompt('设置配置', [
                {label: '名字:', name: 'configName', required: true},
                {label: '路径:', name: 'configPath', type: 'email', required: true}
            ], function (data) {
                if (data) {
                    const newItem = {id: data.configPath, label: data.configName};
                    menuItems.push(newItem);
                    renderMenu();
                }
                console.log('Form Data:', data);
            });
        });

        dropdownMenu.appendChild(addItem);
    }

    document.addEventListener('DOMContentLoaded', function () {

        // 模拟从服务器获取动态数据
        http_post('query_config', menuItems);
    });
</script>

<!--json格式处理-->
<script>
    function json_format() {
        let data = document.getElementById('customTextarea');

        try {
            showAlert("成功")
            let jsonData = JSON.parse(data.value);
            data.value = JSON.stringify(jsonData, null, 4);
        }
        catch (error) {
            showAlert(error, "失败");
        }
    }
</script>

</body>
</html>
